/**
 * 
 */
package cn.ad.server.web.servlet.v2;

import cn.ad.server.web.servlet.v2.requesthandler.ServletRequestHandler;
import cn.ad.server.web.servlet.v2.requesthandler.ServletRequestHandlerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Adserver http请求处理代理类
 * @author Wu Chengjun
 */
public class AdserverHttpProxy implements HttpServletProxy {

	/**
	 * 路径与Handler标识匹配列表
	 * 用于匹配对应的handlerID 来处理对应的PATH路径
	 */
	private Map<String, String> pathHandlerMapper = new HashMap<>();
	
	/**
	 * handle处理实例工厂
	 */
	private ServletRequestHandlerFactory handlerFactory;
	
	
	public AdserverHttpProxy(ServletRequestHandlerFactory handlerFactory) {
		if(handlerFactory == null){
			throw new NullPointerException("There are an exception at structure AdserverHttpProxy: the handlerFactory is null.");
		}
		this.handlerFactory = handlerFactory;
	}
	
	/* (non-Javadoc)
	 * @see cn.falconnect.adserver.adapter.HttpServletProxy#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	public void service(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String contextPath = request.getRequestURI();
		ServletRequestHandler handler = getRequestHandler(contextPath);
		if(handler != null){
				handler.handle(request, response);
		}else{
			throw new Exception("The handler that matched to uri["+ contextPath +"]  is not found");
		}
	}
	
	protected ServletRequestHandler getRequestHandler(String uri){
		String handlerID = null;
		for(String key : pathHandlerMapper.keySet()){
			if(uri.startsWith(key)){
				handlerID = pathHandlerMapper.get(key);
			}
		}
		
		if(handlerID != null){
			return getHandler(handlerID); 
		}else{
			return null;
		}
	}
	
	
	/**
	 * 根据handler id标识获取handler
	 * @param handlerId
	 * @return
	 */
	private ServletRequestHandler getHandler(String handlerId){
		if(handlerFactory == null){
			throw new NullPointerException("the handlerFactory is null.");
		}
		return handlerFactory.getHandler(handlerId);
	}

	/**
	 * @return the pathHandlerMapper
	 */
	public Map<String, String> getPathHandlerMapper() {
		return pathHandlerMapper;
	}

	/**
	 * @param pathHandlerMapper the pathHandlerMapper to set
	 */
	public void setPathHandlerMapper(Map<String, String> pathHandlerMapper) {
		this.pathHandlerMapper = pathHandlerMapper;
	}
}
